﻿using Core.DataAccess.Model.Project.Order;
using Core.Framework.Model.Common;
using Core.IBusiness.IOrderModule;
using System;
using System.Linq;

namespace Core.Business.OrderModule
{
    public class OrderCouponBusiness : IOrderCoupon
    {
        public MethodResult<OrderCoupon> GetOrderCouponByCode(string code)
        {
            try
            {
                using (var context = new ProjectOrderContext())
                {

                    if (code.Length < 6 || code.Length > 8)
                    {
                        return new MethodResult<OrderCoupon>
                        {
                            IsFinished = false,
                            Discription = "输入的优惠卷码不正确"
                        };
                    }

                    var model = context
                                .OrderCoupon
                                .Where(a => a.Code == code.ToLower()).FirstOrDefault();

                    // 是否查询属性
                    if (model != null)
                    {
                        if (model.IsUse)
                        {
                            return new MethodResult<OrderCoupon> { 
                                IsFinished = false, 
                                Discription = "该优惠卷已经使用" 
                            };
                        }
                        else
                        {
                            return new MethodResult<OrderCoupon> { IsFinished = true, Date = model };
                        }
                    }
                    else
                    {
                        return new MethodResult<OrderCoupon> { 
                            IsFinished = false,
                            Discription = "输入的优惠卷码不正确"
                        };
                    }

                }

            }
            catch (Exception e)
            {
                return new MethodResult<OrderCoupon> { IsFinished = false, Discription = e.Message };
            }
        }

        public MethodResult<int> OrderCouponExec(OrderCoupon model, SqlExecType sqlExecType)
        {
            return Utils.SqlExecType<ProjectOrderContext, OrderCoupon>(model,
                        sqlExecType,
                        a => a.Id == model.Id);
        }
    }
}
